package algotithm.weekendrace.leetcode251.test2;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 25068
 * @Date 2021/7/25 10:24
 * @Title 5824. 子字符串突变后可能得到的最大整数
 */
public class Solution {


    public static void main(String[] args) {
        Solution solution = new Solution();
        String num = "334111";
        int[] change = {0,9,2,3,3,2,5,5,5,5};
        String s = solution.maximumNumber(num,change);
        System.out.println(s);
    }


    public String maximumNumber(String num, int[] change) {
        char[] c = num.toCharArray();
        int n = num.length();
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put(i,change[i]);
        }
        boolean[] flag = new boolean[n];
        int cnt = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            int x = (int)(c[i] - '0');
            int y = map.get(x);
            if (x > y) {
                sb.append(x);
            } else if (x < y) {
                if (i > 1 && flag[i - 1] == false && cnt > 0) {
                    sb.append(x);
                    continue;
                } else {
                    sb.append(y);
                    cnt++;
                    flag[i] = true;
                }
            } else {
                if (i > 0 && cnt > 0 && flag[i - 1] == true) {
                    flag[i] = true;

                }
                sb.append(x);
            }
        }
        return sb.toString();
    }
}
